<template>
  <div id="rich"></div>
</template>

<script setup>
import { onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";
import axios from "axios";
import { numberToKM, csvToJson } from "@/utils";

let myRich = null;
let myEchart = null;
onMounted(async () => {
  const { data } = await axios.get(
    "/os/bmw-prod/f129b517-158d-41a9-83a3-3294d639b39e.csv"
  );
  let jsonArray = csvToJson(data);
  // 排序
  jsonArray.sort((a, b) => a.state - b.state);

  // 整理数据
  let map = {};
  for (let key in jsonArray) {
    let item = jsonArray[key];
    if (!map[item.age]) {
      map[item.age] = [item];
    } else {
      map[item.age].push(item);
    }
  }
  for (let key in map) {
    map[key] = map[key]
      .sort((a, b) => a.population - b.population)
      .reverse()
      .slice(0, 6);
  }
  let series = Object.values(map).map((item) => {
    return {
      type: "bar",
      name: item[0].age,
      data: item.map((pop) => pop.population),
      state: item.map((pop) => pop.state),
      showBackground: true,
      backgroundStyle: {
        color: "#f5f5f5",
        borderColor: "#f5f5f5",
        borderWidth: 4,
      },
    };
  });
  let state = series[0].state;
  myRich = document.getElementById("rich");
  myEchart = echarts.init(myRich);
  let option = {
    title: {
      text: "Population by age and state",
      subtext: "It shows the population of U.S. by age and state.",
    },
    grid: {
      top: "20%",
      height: "70%",
    },
    legend: {
      top: 60,
      left: "left",
    },
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: state,
      axisLabel: {
        interval: 0,
        formatter: "{labelDiv|}\n{axisLabelText|{value}}",
        rich: {
          labelDiv: {
            width: 20,
            height: 20,
            backgroundColor: {
              image: "/image/first.svg",
            },
          },
          axisLabelText: {
            color: "red",
          },
        },
      },
    },
    yAxis: {
      axisLabel: {
        padding: 30,
        formatter(value) {
          return numberToKM(value);
        },
      },
    },
    series: series,
  };
  myEchart.setOption(option);
});
onUnmounted(() => {
  myEchart.dispose(myRich);
});
</script>

<style lang="less" scoped>
#rich {
  width: 800px;
  height: 600px;
}
</style>
